package com.pp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pp.bean.PpUser;
import com.pp.bean.ResultPage;
import com.pp.bean.VoPage;
import com.pp.commne.Constant;
import com.pp.mapper.PpUserMapper;
import com.pp.service.IPpUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pp.util.weixin.WxpubOAuth;
import com.pp.util.weixin.bean.OAuthResult;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张子艺
 * @since 2019-03-06
 */
@Service
public class PpUserServiceImpl extends ServiceImpl<PpUserMapper, PpUser> implements IPpUserService {

    @Override
    public PpUser userInfo(String code) throws UnsupportedEncodingException {
        OAuthResult oAuthResult = null;
        oAuthResult = WxpubOAuth.getOpenId(Constant.APPID, Constant.appSecret, code);
        String userInfo = WxpubOAuth.getUserContent(oAuthResult.getAccess_token(), oAuthResult.getOpenid(), Constant.CHINESE);
       System.err.println("userInfo:----"+userInfo);
        Map map = JSONObject.parseObject(userInfo, Map.class);
        String openId = map.get("openid") + "";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("open_id", openId);
        Collection<PpUser> ppUsers = listByMap(paramMap);
        if (ppUsers.size()==0) {
            Long cardNum = baseMapper.findMaxCarNum();
            if (cardNum == null) {
                cardNum = Constant.CAR_NUM;
            } else {
                ++cardNum;
            }
            PpUser ppUser = new PpUser();
            ppUser.setOpenId(openId);
            ppUser.setNickName(map.get("nickname") + "");
            ppUser.setImage(map.get("headimgurl") + "");
            ppUser.setCardNum(cardNum);
            ppUser.setVip(Constant.One_Stra_VIP);
            ppUser.setAllowance(Constant.ALLOWANCE);
            ppUser.setRecommendCount(Constant.RECOMMENDCOUNT);
            ppUser.setCommission(Constant.COMMISSIONS);
            if (this.save(ppUser)) {
                return ppUser;
            }
        } else {
            return new ArrayList<PpUser>(ppUsers).get(0);
        }
        return new PpUser();
    }

    @Override
    public ResultPage<PpUser> findList(VoPage voPage,PpUser ppUser) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        paramMap.put("data", ppUser);
        List<PpUser> list = baseMapper.selectMyPage(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<PpUser> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }
}
